package router

import (
	"context"
	"github.com/gin-gonic/gin"
	"github.com/go-kratos/kratos/v2/errors"
	v1 "go-mall/api/usercenter/v1"
	"go-mall/app/usercenter-svc/internal/service"
	"go-mall/libs/middleware"
	"go-mall/libs/response"
	"log"
)

var (
	userCenter = service.NewUserService()
)

func v1api(group *gin.RouterGroup) {
	group.POST("/login", LoginUser)
	group.POST("/register", RegisterUser)
	group.Use(middleware.JWTAuth())
	group.GET("/getUserInfo", GetUserInfo)
}

func LoginUser(c *gin.Context) {
	var loginReq response.LoginUserReq
	if err := c.BindJSON(&loginReq); err != nil {
		response.NewBindJsonErr(c, nil)
		return
	}
	log.Println("login param:", loginReq)
	req := &v1.LoginUserRequest{
		UserName: loginReq.UserName,
		Password: loginReq.Password,
	}
	defer c.Request.Body.Close()
	resp, _ := userCenter.Login(context.Background(), req)
	if resp != nil {
		response.NewSuccess(c, resp)
		return
	}
	response.NewErrWithCodeAndMsg(c, 30001, "user not found")
}

func RegisterUser(c *gin.Context) {
	var registerReq response.RegisterUserReq
	if err := c.BindJSON(&registerReq); err != nil {
		response.NewBindJsonErr(c, nil)
		return
	}
	req := &v1.RegisterUserRequest{
		UserName: registerReq.UserName,
		Password: registerReq.Password,
		NickName: registerReq.NickName,
		Avatar:   registerReq.Avatar,
	}
	defer c.Request.Body.Close()
	resp, err := userCenter.Register(context.Background(), req)
	if err != nil {
		fromError := errors.FromError(err)
		response.NewErrWithCodeAndMsg(c, fromError.Code, fromError.Message+fromError.Reason)
		return
	}
	response.NewSuccess(c, resp)
}

func GetUserInfo(c *gin.Context) {
	claims, _ := c.Get("claims")
	jwtP := claims.(*middleware.Claims)
	log.Println(jwtP)
	response.NewSuccess(c, jwtP)
}
